package com.fragment;

import static android.content.ContentValues.TAG;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Looper;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baidu.location.demo.FriendRequestActivity;
import com.baidu.location.demo.LoginActivity;
import com.baidu.location.demo.MainActivity;
import com.baidu.location.demo.R;
import com.bumptech.glide.Glide;
import com.entity.FriendRecord;
import com.entity.Friends;
import com.entity.HubMeesageVM;
import com.entity.Response;
import com.entity.User;
import com.listview.PersonalSettingList;
import com.listview.personalSettingAdapter;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogMenuItemView;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogRootLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogView;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.service.HubService;
import com.util.DialogUtil;
import com.util.FileUtil;
import com.util.HttpUtils;

import java.util.ArrayList;
import java.util.List;

public class MineFragment extends Fragment {
    private ImageView mHeadPortrait;
    private TextView mSignature;
    private TextView mName;
    private TextView mUserNumber;
    private ListView personalSetting;
    private personalSettingAdapter personalSettingAdapter;
    private EditText addFrendUserRemark;
    private TextView addFrendUserSignature;
    private TextView addFrendUserNumber;
    private TextView addFrendUserName;
    private ImageView addFrendImage;
    public static List<PersonalSettingList> settingLists=new ArrayList<>();
    public MineFragment() {
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        settingLists.clear();
    }

    public static MineFragment newInstance() {
        return new MineFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_mine, container, false);
    }

    @SuppressLint({"SetTextI18n", "ResourceType"})
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mHeadPortrait=getActivity().findViewById(R.id.headPortrait);
        personalSetting=getActivity().findViewById(R.id.personalSetting);
        mSignature=getActivity().findViewById(R.id.createsignature);
        mName=getActivity().findViewById(R.id.name);
        mUserNumber=getActivity().findViewById(R.id.createuserNumber);
        PersonalSettingList p3=new PersonalSettingList();
        p3.setName("屏幕共享");
        p3.setId(R.drawable.screen);
        p3.setL(view -> {
            new Thread(){
                @Override
                public void run() {
                    super.run();
                    Response<List<Friends>> listResponse=JSONObject.parseObject(HttpUtils.Get("Friends/GetOnLineFriend"), new TypeReference<Response<List<Friends>>>(){});
                    if(listResponse.getStatusCode()==200){
                        String[] items=new String[listResponse.getValue().size()];
                        for (Friends f:listResponse.getValue()) {
                            items[listResponse.getValue().indexOf(f)]=f.getFriend().getName();
                        }
                        getActivity().runOnUiThread(() -> new QMUIDialog.MenuDialogBuilder(getActivity())
                                .setTitle("共享屏幕给好友")
                                .addItems(items, (dialog, which) -> {
                                    HubMeesageVM hubMeesageVM=new HubMeesageVM();
                                    hubMeesageVM.setReceive(listResponse.getValue().get(which).getFriendId());
                                    hubMeesageVM.setData("接受屏幕");
                                    hubMeesageVM.setStatus(0);
                                    HubService.hubConnection.send("SendMessage",JSONObject.toJSONString(hubMeesageVM));
                                    dialog.dismiss();
                                })
                                .addAction("取消", (dialog, index) -> dialog.dismiss())
                                .show());
                    }
                }
            }.start();
        });
        settingLists.add(p3);

        PersonalSettingList p1=new PersonalSettingList();
        p1.setName("添加好友");
        p1.setId(R.drawable.addfriends);
        p1.setL(view -> {
            final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(getActivity());
            builder.setTitle("搜索好友")
                    .setPlaceholder("在此输入好友账号")
                    .setInputType(InputType.TYPE_CLASS_TEXT)
                    .addAction("取消", (dialog, index) -> dialog.dismiss())
                    .addAction("确定", (dialog, index) -> {
                        String text = builder.getEditText().getText().toString();
                        if (text.isEmpty()) {
                            return;
                        }
                        QMUITipDialog qemu= DialogUtil.CreateLog(getActivity(),"",0);
                        dialog.dismiss();
                        new Thread(){
                            @Override
                            public void run() {
                                super.run();
                                Response<User> user= JSONObject.parseObject(HttpUtils.Get("Consumer/GetUser?userNumber="+ text),new TypeReference<Response<User>>(){});
                                getActivity().runOnUiThread(qemu::dismiss);
                                if(user.getStatusCode()==200){
                                    QMUIDialog.CustomDialogBuilder customDialog=new QMUIDialog.CustomDialogBuilder(getActivity()){
                                        @Nullable
                                        @Override
                                        protected View onCreateContent(QMUIDialog dialog, QMUIDialogView parent, Context context) {

                                            return super.onCreateContent(dialog, parent, context);
                                        }

                                        @Override
                                        protected void onAfterCreate(@NonNull QMUIDialog dialog, @NonNull QMUIDialogRootLayout rootLayout, @NonNull Context context) {
                                            super.onAfterCreate(dialog, rootLayout, context);
                                            User data=user.getValue();
                                            addFrendImage= rootLayout.findViewById(R.id.addFrendImage);
                                            addFrendUserName=rootLayout.findViewById(R.id.addFrendUserName);
                                            addFrendUserNumber=rootLayout.findViewById(R.id.addFrendUserNumber);
                                            addFrendUserSignature=rootLayout.findViewById(R.id.addFrendUserSignature);
                                            addFrendUserRemark=rootLayout.findViewById(R.id.addFrendUserRemark);
                                            Glide.with(context).load(data.getHeadPortrait()).into(addFrendImage);
                                            addFrendUserName.setText(data.getName());
                                            addFrendUserNumber.setText(data.getUserNumber());
                                            addFrendUserSignature.setText(data.getSignature());
                                        }
                                    }.setLayout(R.layout.addfriendlayout);

                                    customDialog.addAction("取消", (dialog1, index1) -> {
                                        dialog1.dismiss();
                                    });
                                    customDialog.addAction("添加好友", (dialog12, index12) -> {
                                        FriendRecord friendRecord=new FriendRecord();
                                        friendRecord.setRemark(addFrendUserRemark.getText().toString());
                                        friendRecord.setRespondentId(user.getValue().getId());
                                        String json =JSONObject.toJSONString(friendRecord);
                                         new Thread(){
                                            @Override
                                            public void run() {
                                                super.run();
                                                Response<String> data=JSONObject.parseObject(HttpUtils.Post("Friends/ApplyForFrien",json),new TypeReference<Response<String>>(){});
                                                if(data.getStatusCode()==200){
                                                    DialogUtil.CreateDoalog(getActivity(),"发起申请成功",2000,QMUITipDialog.Builder.ICON_TYPE_SUCCESS);
                                                }else{
                                                    DialogUtil.CreateDoalog(getActivity(),data.getMessage(),2000,QMUITipDialog.Builder.ICON_TYPE_FAIL);

                                                }
                                                getActivity().runOnUiThread(dialog12::dismiss);
                                            }
                                        }.start();
                                    });
                                    getActivity().runOnUiThread(() -> {
                                        customDialog.create();
                                        customDialog.show();
                                    });

                                }else {
                                    DialogUtil.CreateDoalog(getActivity(),user.getMessage(),0,QMUITipDialog.Builder.ICON_TYPE_FAIL);
                                }
                            }
                        }.start();
                    })
                    .create().show();
        });
        settingLists.add(p1);
        PersonalSettingList p2=new PersonalSettingList();
        p2.setName("好友记录");
        p2.setId(R.drawable.applicationrecord);
        p2.setL(view -> {
            startActivity(new Intent(getActivity(), FriendRequestActivity.class));
        });
        settingLists.add(p2);
        PersonalSettingList p=new PersonalSettingList();
        p.setName("退出登录");
        p.setId(R.drawable.logout);
        p.setL(view -> {
            FileUtil.Delete(getActivity(),"user.json");
            getActivity().startActivity(new Intent(getActivity(), LoginActivity.class));
            getActivity().finish();
        });
        settingLists.add(p);

        personalSettingAdapter=new personalSettingAdapter(getActivity(),R.layout.personalsettinglayout,settingLists);
        personalSetting.setAdapter(personalSettingAdapter);
        new Thread(){
            @Override
            public void run() {
                super.run();
                for (int i = 0; i < 500; i++) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if(MainActivity.user!=null){
                        getActivity().runOnUiThread(() -> {
                            mSignature.setText("个性签名："+MainActivity.user.getSignature());
                            mUserNumber.setText(MainActivity.user.getUserNumber());
                            mName.setText(MainActivity.user.getName());
                            Glide.with(getActivity()).load(MainActivity.user.getHeadPortrait()).into(mHeadPortrait);
                        });
                        return;
                    }
                }
            }
        }.start();

    }

    @Override
    public void onStart() {
        super.onStart();

    }
}